package a1;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TextAreaToTable extends JFrame {
    private final JTextArea jTextArea = new JTextArea(10, 30);
    private final JPanel panel = new JPanel();

    public TextAreaToTable() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        getContentPane().setLayout(null);

        // 添加文本域和面板
        setTextarea();

        // 添加按钮
        JButton tableButton = new JButton("显示表格");
        tableButton.setBounds(50, 50, 120, 30);
        tableButton.addActionListener(e -> showTable());
        getContentPane().add(tableButton);

        setVisible(true);
    }

    public void setTextarea() {
        Font font = new Font("微软雅黑", Font.BOLD, 14);
        jTextArea.setFont(font);
        panel.setBounds(250, 300, 450, 200);
        for (int i = 0; i < 10; i++) {
            jTextArea.append("数据" + i + ",列1,列2,列3\n"); // 每行以逗号分隔不同的列数据
        }
        JScrollPane scrollPane = new JScrollPane(jTextArea);
        panel.add(scrollPane);
        getContentPane().add(panel);
    }

    public void showTable() {
        // 解析文本数据为二维表格数据
        List<String> lines = Arrays.asList(jTextArea.getText().split("\n"));
        List<List<String>> tableData = new ArrayList<>();
        for (String line : lines) {
            String[] columns = line.split(",");
            tableData.add(Arrays.asList(columns));
        }

        // 创建表格模型
        int columnCount = tableData.get(0).size();
        String[] columnNames = new String[columnCount];
        for (int i = 0; i < columnCount; i++) {
            columnNames[i] = "列" + (i + 1);
        }
        Object[][] rowData = new Object[tableData.size()][columnCount];
        for (int i = 0; i < tableData.size(); i++) {
            List<String> row = tableData.get(i);
            for (int j = 0; j < columnCount; j++) {
                rowData[i][j] = row.get(j);
            }
        }
        DefaultTableModel tableModel = new DefaultTableModel(rowData, columnNames);

        // 创建表格组件并展示
        JTable jTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(jTable);
        scrollPane.setPreferredSize(new Dimension(600, 400));
        JOptionPane.showMessageDialog(this, scrollPane);
    }

    public static void main(String[] args) {
        new TextAreaToTable();
    }
}
